/**
 * 跳舞动画模块 - 独立于PixiCharacter核心功能
 * 提供一键跳舞功能，包括角色动画、换衣服和背景动画
 */
class DanceAnimation {
    constructor(character, clothesOptions = []) {
        this.character = character;
        this.clothesOptions = clothesOptions;
        this.isDancing = false;
        this.animationInterval = null;
        this.backgroundInterval = null;
        this.clothesInterval = null;
        this.originalBackgroundColor = null;
        this.currentClothesIndex = 0;
        
        // 创建独立的动画管理器
        this.animationManager = {
            animations: new Map(),
            isAnimating: false,
            
            // 简单的动画执行器
            async executeAnimation(animationName, duration = 1000) {
                if (this.isAnimating) return;
                this.isAnimating = true;
                
                return new Promise((resolve) => {
                    setTimeout(() => {
                        this.isAnimating = false;
                        resolve();
                    }, duration);
                });
            }
        };
    }

    /**
     * 开始跳舞
     */
    async startDance() {
        if (this.isDancing) return;
        
        this.isDancing = true;
        console.log('🎵 开始跳舞！');
        
        // 保存原始背景色
        this.originalBackgroundColor = document.body.style.backgroundColor;
        
        // 并行执行各种动画
        this.startCharacterDance();
        this.startBackgroundAnimation();
        this.startClothesAnimation();
    }

    /**
     * 停止跳舞
     */
    stopDance() {
        if (!this.isDancing) return;
        
        this.isDancing = false;
        console.log('🛑 停止跳舞');
        
        // 停止所有动画
        this.stopCharacterDance();
        this.stopBackgroundAnimation();
        this.stopClothesAnimation();
        
        // 恢复原始背景色
        if (this.originalBackgroundColor) {
            document.body.style.backgroundColor = this.originalBackgroundColor;
        }
    }

    /**
     * 角色舞蹈动画
     */
    startCharacterDance() {
        const characterAnimations = [
            () => this.character.spin(),
            () => this.character.jump(),
            () => this.character.wave(),
            () => this.character.bounce(),
            () => this.character.shake(),
            () => this.character.move(50, 0).then(() => this.character.move(-50, 0))
        ];

        let animationIndex = 0;
        
        this.animationInterval = setInterval(async () => {
            if (!this.isDancing) return;
            
            try {
                const animation = characterAnimations[animationIndex % characterAnimations.length];
                await animation();
                animationIndex++;
            } catch (error) {
                console.warn('角色动画执行失败:', error);
            }
        }, 2000); // 每2秒执行一个动画
    }

    /**
     * 停止角色舞蹈
     */
    stopCharacterDance() {
        if (this.animationInterval) {
            clearInterval(this.animationInterval);
            this.animationInterval = null;
        }
    }

    /**
     * 背景颜色动画
     */
    startBackgroundAnimation() {
        const colors = [
            '#ff6b6b', // 红色
            '#4ecdc4', // 青色
            '#45b7d1', // 蓝色
            '#96ceb4', // 绿色
            '#feca57', // 黄色
            '#ff9ff3', // 粉色
            '#54a0ff', // 深蓝色
            '#5f27cd'  // 紫色
        ];

        let colorIndex = 0;
        
        this.backgroundInterval = setInterval(() => {
            if (!this.isDancing) return;
            
            const currentColor = colors[colorIndex % colors.length];
            this.animateBackgroundColor(currentColor);
            colorIndex++;
        }, 1500); // 每1.5秒换一次颜色
    }

    /**
     * 停止背景动画
     */
    stopBackgroundAnimation() {
        if (this.backgroundInterval) {
            clearInterval(this.backgroundInterval);
            this.backgroundInterval = null;
        }
    }

    /**
     * 衣服切换动画
     */
    startClothesAnimation() {
        if (this.clothesOptions.length === 0) return;
        
        this.clothesInterval = setInterval(async () => {
            if (!this.isDancing) return;
            
            try {
                const clothesPath = this.clothesOptions[this.currentClothesIndex % this.clothesOptions.length];
                if (clothesPath) {
                    await this.character.setClothes(clothesPath);
                    console.log('👕 换衣服:', clothesPath);
                }
                this.currentClothesIndex++;
            } catch (error) {
                console.warn('换衣服失败:', error);
            }
        }, 3000); // 每3秒换一次衣服
    }

    /**
     * 停止衣服动画
     */
    stopClothesAnimation() {
        if (this.clothesInterval) {
            clearInterval(this.clothesInterval);
            this.clothesInterval = null;
        }
    }

    /**
     * 背景颜色渐变动画
     */
    animateBackgroundColor(targetColor) {
        const startColor = this.getComputedBackgroundColor();
        const duration = 1000; // 1秒渐变
        const startTime = Date.now();
        
        const animate = () => {
            const elapsed = Date.now() - startTime;
            const progress = Math.min(elapsed / duration, 1);
            
            const interpolatedColor = this.interpolateColor(startColor, targetColor, progress);
            document.body.style.backgroundColor = interpolatedColor;
            
            if (progress < 1 && this.isDancing) {
                requestAnimationFrame(animate);
            }
        };
        
        animate();
    }

    /**
     * 获取当前背景色
     */
    getComputedBackgroundColor() {
        const computed = window.getComputedStyle(document.body);
        return computed.backgroundColor || '#ffffff';
    }

    /**
     * 颜色插值
     */
    interpolateColor(color1, color2, factor) {
        // 简单的颜色插值，将颜色转换为RGB
        const rgb1 = this.hexToRgb(color1) || { r: 255, g: 255, b: 255 };
        const rgb2 = this.hexToRgb(color2) || { r: 255, g: 255, b: 255 };
        
        const r = Math.round(rgb1.r + (rgb2.r - rgb1.r) * factor);
        const g = Math.round(rgb1.g + (rgb2.g - rgb1.g) * factor);
        const b = Math.round(rgb1.b + (rgb2.b - rgb1.b) * factor);
        
        return `rgb(${r}, ${g}, ${b})`;
    }

    /**
     * 十六进制颜色转RGB
     */
    hexToRgb(hex) {
        if (!hex || hex.length < 3) return null;
        
        // 移除#号
        hex = hex.replace('#', '');
        
        // 处理3位和6位十六进制
        if (hex.length === 3) {
            hex = hex.split('').map(char => char + char).join('');
        }
        
        const result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }

    /**
     * 延迟函数
     */
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

// 导出到全局
if (typeof window !== 'undefined') {
    window.DanceAnimation = DanceAnimation;
} 